//
//  Emoticon.m
//  XinLang_OC
//
//  Created by WONG on 16/4/23.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "Emoticon.h"
#import "EmoticonTextAttachment.h"
#import "EmoticonPackage.h"

@implementation Emoticon

- (instancetype)initWithId:(NSString *)id dict:(NSDictionary *)dict {
    if(self = [super init]) {
        self.id = id;
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+ (instancetype)initWithId:(NSString *)id dict:(NSDictionary *)dict {
    return [[Emoticon alloc] initWithId:id dict:dict];
}

- (instancetype)initWithRemoveEmoticon:(BOOL)removeEmoticon {
    if (self = [super init]) {
        self.removeEmoticon = removeEmoticon;
    }
    return self;
}

+ (instancetype)initWithRemoveEmoticon:(BOOL)removeEmoticon {
    return [[Emoticon alloc] initWithRemoveEmoticon:removeEmoticon];
}


// 字典的key在模型中找不到对应的属性
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {}

- (NSString *)description {
    return nil;
}

- (void)setPng:(NSString *)png {
    _png = png;
    
    // 计算图片的完整路径 = bundlePath + 表情包文件夹名称 + 图片名称
    self.pngPath = [bundlePath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@/%@",self.id,self.png]];
}

- (void)setCode:(NSString *)code {
    _code = code;
    
    // 扫描   swift中的做法
//    NSScanner *scanner = [[NSScanner alloc] initWithString:code];
//    // result: UnsafeMutablePointer<UInt32>: UInt32指针
//    UInt32 result = 0;
//    // 将结果赋值给result
//    [scanner scanHexInt:&result];
    
    /*
        将16进制的字符转换为emoji表情
     */
    unsigned long unicodeIntValue = strtoul([code UTF8String], 0, 16);
    NSString *sendStr = [[NSString alloc] initWithBytes:&unicodeIntValue length:4 encoding:NSUTF32LittleEndianStringEncoding];
    
    self.emoji = sendStr;
}

/**
 根据表情模型创建带表情图片的属性文本
 
 - parameter font: font
 
 - returns: 带表情图片的属性文本
 */
- (NSAttributedString *)emoticonToAttrString:(UIFont *)font {
    // 判断是否有图片
    if (!self.pngPath) {
        return [[NSAttributedString alloc] initWithString:@""];
    }
    
    // 创建附本
    EmoticonTextAttachment *attachment = [EmoticonTextAttachment new];
    CGFloat width = font.lineHeight;
    
    // 设置附文本的大小
    attachment.bounds = CGRectMake(0, -4, width, width);
    
    // 给附件添加图片
    attachment.image = [UIImage imageWithContentsOfFile:self.pngPath];

    // 将表情名称赋值给attachment附件
    attachment.name = self.chs;
    
    // 创建一个属性文本，属性文本有一个附件，附件里面有一张图片
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
    
    // 附件没有Font属性,会变小
    // 给附件添加Font属性
    [attrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, 1)];
    
    return attrString;
}

/**
 根据表情名称获取对应的表情模型
 
 - parameter string: 表情模型
 */
+ (Emoticon *)stringToEmoticon:(NSString *)chs {
    // 根据表情名称获取对应的表情模型
    // 判断 chs 传入的表情名称是否等于模型里面的chs
    
    // 表情包 -> 表情模型
    // 遍历表情包里面的所有表情模型
    for (EmoticonPackage *package in [EmoticonPackage loadPackages]) {
        for (Emoticon *emoticon in package.emoticons) {
            if ([chs isEqualToString:emoticon.chs]) {
                return emoticon;
            }
        }
    }
    return nil;
}

/**
    将带表情字符串的微博内容转成带表情图片的微博内容
 */
+ (NSAttributedString *)stringToEmoticonString:(NSString *)text {
    // 1.从微博内容中截取表情文本
    // [ ] 在正则表达式里面是有特殊含义的,需要转义
    NSError *error = nil;
    NSRegularExpression *regular = [[NSRegularExpression alloc] initWithPattern:@"\\[.*?\\]" options:NSRegularExpressionDotMatchesLineSeparators error:&error];
    if (error) {
        NSLog(@"正则表达式error = %@",error);
    }
    
    // 匹配
    NSArray *results = [regular matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    
    // 将传入的内容转成属性文本(普通的文本是不能将属性文本替换进去)
    NSMutableAttributedString *attrM = [[NSMutableAttributedString alloc] initWithString:text];
    
    // 匹配结果的数量
    NSInteger count = results.count;
    
    // 反过来替换内容,从匹配结果数组后面往前面替换
    for (NSInteger i = (count - 1); i >= 0; i--) {
        NSTextCheckingResult *result = results[i];
        NSRange range = [result rangeAtIndex:0];
        // 截取表情名称
        NSString *emoticonString = [text substringWithRange:range];
        
        // 根据表情的名称获取对应的表情模型
        Emoticon *emoticon = [Emoticon stringToEmoticon:emoticonString];
        
        if (emoticon) {
            // 找到的表情模型
            // attrString 带表情图片的属性字符串
            NSAttributedString *attrString = [emoticon emoticonToAttrString:[UIFont systemFontOfSize:14]];
            [attrM replaceCharactersInRange:range withAttributedString:attrString];
        }
    }
    
    return attrM;
}





@end




















